package com.cavemanst.tictactoe;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainSurfaceView extends SurfaceView  implements SurfaceHolder.Callback, Runnable{

	private boolean m_is_running, m_is_game_pause;
	private SurfaceHolder m_surfaceholder;
	private static int s_screen_width, s_screen_height;
	private Paint paint;
	private Thread m_mainthread;
	private Rectangle[] rect_array = new Rectangle[9];
	
	public MainSurfaceView(Context context) {
		super(context);
		m_surfaceholder = getHolder();
		m_surfaceholder.addCallback(this);
		setFocusable(true);
		s_screen_width = context.getResources().getDisplayMetrics().widthPixels;
		s_screen_height = context.getResources().getDisplayMetrics().heightPixels;
	}

	private void Initialize(){
		paint = new Paint();
		m_mainthread = new Thread(this);
		m_mainthread.start();
		m_is_game_pause = false;
		m_is_running = true;
		
	}
	
	private void Game_Update(){
		
	}
	
	private void Game_Draw(Canvas canvas){
		canvas.drawColor(Color.WHITE);
		paint.setColor(Color.GRAY);
		canvas.drawLine(0, s_screen_height/3, s_screen_width, s_screen_height/3, paint);
		canvas.drawLine(0, (s_screen_height - s_screen_height/3), s_screen_width, (s_screen_height - s_screen_height/3), paint);
		canvas.drawLine(s_screen_width/3, 0, s_screen_width/3, s_screen_height, paint);
		canvas.drawLine((s_screen_width - s_screen_width/3), 0, (s_screen_width - s_screen_width/3), s_screen_height, paint);
	}
	

	@Override
	public void run() {
		while(m_is_running){
			if (!m_is_game_pause){
				try{
					// Thread.sleep(20);
				}catch(Exception e){}
				Game_Update();
				Canvas m_lockcanvas = m_surfaceholder.lockCanvas(null);
				synchronized (m_surfaceholder) {
					if(m_lockcanvas != null){
						Game_Draw(m_lockcanvas);
						m_surfaceholder.unlockCanvasAndPost(m_lockcanvas);
					}
				}
			}
		}
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		Initialize();
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		m_is_running = false;
        do {
            try {
                m_mainthread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);
		
	}

}
